/**
 * 2010(c) Copyright Oceansoft Information System Co.,LTD. All rights reserved.
 * <p>
 * Compile: JDK 1.6+
 * <p>
 * 版权所有(C)：江苏欧索软件有限公司
 * <p>
 * 公司名称：江苏欧索软件有限公司
 * <p>
 * 公司地址：中国苏州科技城青山路1号
 * <p>
 * 网址: http://www.oceansoft.com.cn
 * <p>
 * 作者: 090922(陈伟)
 * <p>
 * 文件名: com.oceansoft.mobile.biz.admin.service.impl.AttachmentServiceImpl.java 
 * <p>
 * 类产生时间: 2014/4/10 15:23
 * <p>
 * 负责人: 090922(陈伟)
 * <p>
 * Email:javacspring@gmail.com
 * <p>
 * 所在组 : 掌上公安应用平台
 * <p>
 * 所在部门: 开发部--手持技术部
 * <p>
 * <p>
 */
package com.oceansoft.mobile.biz.admin.service;

import static com.oceansoft.mobile.common.Constant.DB_OPER_ONE_SUCC;

import java.io.File;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.oceansoft.mobile.biz.admin.entity.BasesiteArticlePic;
import com.oceansoft.mobile.common.base.entity.Result;
import com.oceansoft.mobile.common.dao.ICommonDao;

/**
 * 附件处理业务组件接口实现类
 *
 * @author: qiur
 */
@Service
@Transactional(readOnly = true)
public class BaseSiteAttachmentServiceImpl implements IBaseSiteAttachmentService {

    @Resource
    private ICommonDao commonDao;

    @Override
    @Transactional
    public long savePic(BasesiteArticlePic productPic) {
    	long r= commonDao.saveOne("INSERT INTO SITE_PICS(PID,AUTHOR,SIZE,DPI,TIME,SUMMARY,URL,TITLE,FILE_NAME,ORIG_NAME,CATALOG) VALUES(:productId,:author,:fileSize,:dpi,:time,:summary,:url,:title,:fileName,:originalName,:catalog)", productPic);
    	return r;
    }

    @Override
    @Transactional
    public Result deletePicById(String root, long id) {
    	BasesiteArticlePic file = commonDao.loadOne("SELECT T.URL FROM SITE_PICS T WHERE T.ID = ?", BasesiteArticlePic.getUrlRowMapper(), id);
        if (null != file) {
            //1.删除数据库记录
            int rt = commonDao.deleteOne("DELETE FROM SITE_PICS WHERE ID = ? ", id);
            //TODO:先删除记录or先删除磁盘文件？？？
            if (DB_OPER_ONE_SUCC != rt) {
                return new Result(Result.FAILURE, "删除文件失败");//数据库记录删除失败
            }
            //2.删除文件系统图片
            boolean b = FileUtils.deleteQuietly(new File(String.format("%1$s%2$s", root, file.getUrl())));
            if (b) {
                return new Result(id);
            } else {
                //                throw new RuntimeException("删除文件失败");
                return new Result(Result.SUCC, "删除文件失败");
            }
        } else {
            return new Result(Result.FAILURE, "该文件不存在");
        }
    }

    @Override
    public List<BasesiteArticlePic> loadProductPics(long productId) {
        return commonDao.loadList("SELECT * FROM SITE_PICS T WHERE T.PID = ? AND T.TOP_FLAG = 0", BasesiteArticlePic.getFullRowMapper(), productId);
    }
}
